package com.csnj.core.Srvs.SysManager;

import com.csnj.common.biz.BaseBiz;
import com.csnj.common.constant.UserConstant;
import com.csnj.common.exception.IRCException;
import com.csnj.core.constant.CoreConstants;
import com.csnj.core.dao.SysUserMapper;
import com.csnj.core.entity.SysUser;
import com.csnj.core.exception.DataNotExistException;
import com.csnj.core.exception.PasswordErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by xiabin on 2018/11/20.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysUserSrvs extends BaseBiz<SysUserMapper, SysUser> {
    @Override
    public void insertSelective(SysUser entity) {
        String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(entity.getPassword());
        entity.setPassword(password);
        super.insertSelective(entity);
    }
    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    public SysUser getUserByUsername(String username){
        SysUser user = new SysUser();
        user.setUsername(username);
        return mapper.selectOne(user);
    }

    public List<SysUser> GetAllUser(){
        return mapper.getAllUser();
    }


    public SysUser ChangePwd(Integer userId, String oldpwd, String newpwd) throws IRCException {
        SysUser user = mapper.selectByPrimaryKey(userId);
        if(user==null) {
            throw new DataNotExistException(CoreConstants.MSG_DATA_NOT_EXIST);
        }
        BCryptPasswordEncoder ec =  new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT);
        if(ec.matches(oldpwd, user.getPassword())) {
            user.setPassword(ec.encode(newpwd));
            updateSelectiveById(user);
        } else {
            throw new PasswordErrorException(CoreConstants.MSG_PASSWORD_ERROR);
        }
        return user;
    }

    public Boolean ResetPwd(Integer uid) throws DataNotExistException {
        SysUser user = mapper.selectByPrimaryKey(uid);
        if(user==null) {
            throw new DataNotExistException(CoreConstants.MSG_DATA_NOT_EXIST);
        }
        BCryptPasswordEncoder ec =  new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT);
        user.setPassword(ec.encode("888888"));
        updateSelectiveById(user);
        return true;
    }
}
